//
//  BSPayManager.swift
//  MiTao
//
//  Created by zhang qiang on 2018/12/12.
//  Copyright © 2018 DDC. All rights reserved.
//

import Foundation

enum PayType: String {
    case wp
}

enum PayCode: Int {
    /// 微信支付成功
    case WXSUCESS = 1001
    
    /// 微信支付失败
    case WXERROR = 1002
    
    /// 微信取消支付
    case WXSCANCEL = 1003
    
    /// 未安装微信
    case WXERROR_NOTINSTALL = 1004
    
    /// 微信不支持
    case WXERROR_UNSUPPORT = 1005
    
    /// 微信支付参数解析错误
    case WXERROR_PARAM = 1006
}
class MTPayManager: NSObject {
    static let manager = MTPayManager()
    
    private var pay_result:((_ pay_code: PayCode) -> ())?
    
    /// 需要天上微信 appid
    func registAppid() {
        WXApi.registerApp(AppConfig.wechatAppKey, universalLink: AppConfig.wechatUnlink)
        //registerApp(AppConfig.wechatAppKey, enableMTA: false)
    }
    //MARK: --------微信支付
    func wxPay(pay_param: WhchatPayModel,
               payResult:@escaping ((_ pay_code: PayCode) -> ())) {
        pay_result = payResult
        
        WXApi.registerApp(pay_param.appid, universalLink: AppConfig.wechatUnlink)
        if !WXApi.isWXAppInstalled() {
            pay_result!(PayCode.WXERROR_NOTINSTALL)
            return
        }
        if !WXApi.isWXAppSupport() {
            pay_result!(PayCode.WXERROR_UNSUPPORT)
            return
        }
        
        let req = PayReq.init()
        //商户号
        req.partnerId = pay_param.partnerid
        //微信返回的支付交易会话ID
        req.prepayId = pay_param.prepayid
        // 随机字符串,不长于32位
        req.nonceStr = pay_param.noncestr
        // 时间戳
        req.timeStamp = UInt32(pay_param.timestamp)
        //暂填写固定值Sign=WXPay
        req.package = pay_param.package
        //签名
        req.sign = pay_param.sign
        WXApi.send(req)
        
        
    }
    
    func handleOpenURL(url: URL) -> Bool {
        if url.host == "pay" {
            return WXApi.handleOpen(url, delegate: self)
        }
        return true
    }
    
}

extension MTPayManager: WXApiDelegate {
    
    func onResp(_ resp: BaseResp!) {
        if resp.isKind(of: PayResp.self) {
            switch resp.errCode {
            case 0:  //WXSuccess
                pay_result!(PayCode.WXSUCESS)
                break
            case -2: //WXErrCodeUserCancel
                pay_result!(PayCode.WXSCANCEL) ////用户点击取消并返回
                break
            default:
                pay_result!(PayCode.WXERROR)
                break
            }
        }
    }
}
